Reorder List
Question
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
Analysis
- 将一个链表以中点分为两段 l1,l2,并将 l2 reverse
- 遍历两个链表,将第二半链表中的点依次插入第一个链表中
- 注意在遍历插入节点之前先将第一半链表最后节点置空null
Code
|
|
Partition List
Question
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
Analysis
两个链表分别代表依次插入符合条件的节点,最后连接在一起,注意将结果链表尾节点置空。
Code
|
|